package com.spark.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spark.common.core.Result;
import com.spark.common.core.api.SparkCommonApi;
import com.spark.common.core.entity.system.SysDictItem;
import com.spark.common.query.QueryGenerator;
import com.spark.common.core.entity.system.SysDict;
import com.spark.common.utils.DictUtils;
import com.spark.modules.system.service.ISysDictItemService;
import com.spark.modules.system.service.ISysDictService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 系统数据字典Controller
 *
 * @author LYCHEE
 * @date 2025/02/20 10:20
 */
@RestController
@RequestMapping(value = "/sys/dict")
public class SysDictController {

    @Resource
    private ISysDictService sysDictService;
    @Resource
    private ISysDictItemService sysDictItemService;
    @Resource
    private SparkCommonApi sparkCommonApi;

    /**
     * 初始化数据字典缓存
     */
    @PostConstruct
    public void init(){
        sparkCommonApi.refreshDictCache(true);
    }

    /**
     * 分页列表查询
     *
     * @param sysDict 系统数据字典对象
     * @param pageNo   分页
     * @param pageSize 分页
     * @return 系统数据字典列表
     */
    @PreAuthorize("@sp.hasPerm('sys:dict:query')")
    @GetMapping(value = "/queryPageList")
    public Result<?> queryPageList(SysDict sysDict,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict);
        Page<SysDict> page = new Page<SysDict>(pageNo, pageSize);
        IPage<SysDict> pageList = sysDictService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 列表查询
     *
     * @param sysDict 系统数据字典对象
     * @return 系统数据字典列表
     */
    @PreAuthorize("@sp.hasPerm('sys:dict:query')")
    @GetMapping(value = "/queryList")
    public Result<?> queryList(SysDict sysDict) {
        QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict);
        List<SysDict> list = sysDictService.list(queryWrapper);
        return Result.ok(list);
    }

    /**
     * 通过ID查询
     *
     * @param id 主键
     * @return 系统数据字典对象
     */
    @PreAuthorize("@sp.hasPerm('sys:dict:queryById')")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam String id) {
        SysDict sysDict = sysDictService.getById(id);
        if (Objects.isNull(sysDict)) {
            return Result.fail("数据获取失败");
        }
        return Result.ok(sysDict);
    }

    /**
     * 新增
     *
     * @param sysDict 系统数据字典对象
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:dict:add')")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SysDict sysDict) {
        boolean save = sysDictService.save(sysDict);
        return Result.flag(save);
    }

    /**
     * 编辑
     *
     * @param sysDict 系统数据字典对象
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:dict:edit')")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody SysDict sysDict) {
        boolean update = sysDictService.updateById(sysDict);
        return Result.flag(update);
    }

    /**
     * 通过id删除
     *
     * @param id 主键
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:dict:del')")
    @Transactional(rollbackFor = {Exception.class})
    @DeleteMapping(value = "/delete/{id}")
    public Result<?> delete(@PathVariable(name = "id") String id) {
        // 删除子表数据
        LambdaQueryWrapper<SysDictItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysDictItem::getDictId, id);
        boolean remove = sysDictItemService.remove(lambdaQueryWrapper);
        if (remove){
            boolean update = sysDictService.removeById(id);
            return Result.flag(update);
        }
        return Result.flag(false);
    }

    /**
     * 通过id批量删除删除
     *
     * @param ids 主键
     * @return 成功或失败
     */
    @Transactional(rollbackFor = {Exception.class})
    @DeleteMapping(value = "/deleteBatchByIds/{ids}")
    public Result<?> deleteBatchByIds(@PathVariable(name = "ids") String[] ids) {
        List<String> list = Arrays.asList(ids);
        // 删除子表数据
        LambdaQueryWrapper<SysDictItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SysDictItem::getDictId, list);
        boolean remove = sysDictItemService.remove(lambdaQueryWrapper);
        if (remove){
            boolean update = sysDictService.removeBatchByIds(Arrays.asList(ids));
            return Result.flag(update);
        }
        return Result.flag(false);
    }

    /**
     * 刷新缓存
     * @return 成功与否
     */
    @PreAuthorize("@sp.hasPerm('sys:dict:refreshCache')")
    @GetMapping(value = "/refreshCache")
    public Result<?> refreshCache(){
        sparkCommonApi.refreshDictCache(true);
        return Result.ok("刷新成功");
    }

    /**
     * 获取缓存的字典项数据
     * @param dictCode 字典编码
     * @return
     */
    @GetMapping(value = "/queryDictCache")
    public Result<?> queryDictCache(@RequestParam String dictCode){
        List<String> dictCodes = Arrays.asList(dictCode.split(","));
        List<SysDictItem> dictItem = DictUtils.getDictItemByDictCodes(dictCodes);
        return Result.ok(dictItem);
    }
}
